package com.fzt.system.service.security;

import com.fzt.common.constant.RedisKeys;
import com.fzt.framework.utils.RedisUtils;
import com.fzt.system.domain.vo.CaptchaVO;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * <p>
 *
 * </p>
 *
 * @author 非洲铜
 * @since 2022-12-08
 */
@AllArgsConstructor
@Service
public class CaptchaService {

    private final RedisUtils redisUtils;

    /**
     * 生成验证码
     */
    public CaptchaVO generate() {
        // 生成验证码key
        String key = UUID.randomUUID().toString();

        // 生成验证码
        SpecCaptcha captcha = new SpecCaptcha(120, 40);
        captcha.setLen(4);
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        String image = captcha.toBase64();

        // 保存到缓存
        String redisKey = RedisKeys.getCaptchaKey(key);
        //todo 开发临时改成24小时
        // redisUtils.set(redisKey, captcha.text(), 300);
        redisUtils.set(redisKey, captcha.text());

        // 封装返回数据
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setKey(key);
        captchaVO.setImage(image);

        return captchaVO;
    }

    /**
     * 验证码效验
     *
     * @param key  key
     * @param code 验证码
     * @return true：成功  false：失败
     */
    boolean validate(String key, String code) {
        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(code)) {
            return false;
        }

        // 获取redis中的验证码
        String captcha = getCache(key);

        return code.equalsIgnoreCase(captcha);
    }


    private String getCache(String key) {
        key = RedisKeys.getCaptchaKey(key);
        String captcha = (String) redisUtils.get(key);
        // todo 开发 暂时不删除  删除验证码
//        if (captcha != null) {
//            redisUtils.delete(key);
//        }

        return captcha;
    }
}
